/*
*Copyright 2021-2023 NERCIS
*
*Licensed under the Apache License, Version 2.0 (the "License");
*you may not use this file except in compliance with the License.
*You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
*Unless required by applicable law or agreed to in writing, software
*distributed under the License is distributed on an "AS IS" BASIS,
*WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*See the License for the specific language governing permissions and
*limitations under the License.
*/

package cn.ac.nercis.pes.community.controller.evaluation.planning;

import cn.ac.nercis.pes.common.constant.knowledge.TargetType;
import cn.ac.nercis.pes.common.constant.project.FinishState;
import cn.ac.nercis.pes.community.component.controls.MenuListCell;
import cn.ac.nercis.pes.community.component.dialog.MessageDialog;
import cn.ac.nercis.pes.community.component.dialog.MessageType;
import cn.ac.nercis.pes.community.controller.base.InitEvalDataLoad;
import cn.ac.nercis.pes.community.model.vo.MenuVO;
import cn.ac.nercis.pes.community.utils.AppStore;
import cn.ac.nercis.pes.community.utils.ControlUtils;
import cn.ac.nercis.pes.community.utils.LogUtils;
import cn.ac.nercis.pes.community.utils.SpringUtils;
import cn.ac.nercis.pes.community.views.evaluation.planning.SpecialTargetView;
import cn.ac.nercis.pes.community.views.evaluation.planning.StandardTargetView;
import cn.ac.nercis.pes.model.dto.project.SystemProcessDTO;
import cn.ac.nercis.pes.model.dto.target.LayerTargetDTO;
import cn.ac.nercis.pes.service.project.SystemProcessService;
import cn.ac.nercis.pes.service.project.SystemTargetService;
import javafx.application.Platform;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.ListView;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.StackPane;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.net.URL;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * 测评指标确认管理控制器
 *
 * @author zpy
 * @version 1.0.0
 */
@Slf4j
public class TargetConfirmController implements Initializable, InitEvalDataLoad {

    @FXML
    private StackPane page;
    @FXML
    private BorderPane bodyPane;
    @FXML
    private ListView<MenuVO> tecMenus;
    @FXML
    private ListView<MenuVO> manageMenus;

    private final SystemTargetService systemTargetService;
    private final SystemProcessService systemProcessService;

    private final ExecutorService executor;
    private final List<LayerTargetDTO> layerTargets = new ArrayList<>();

    private String currentSystemId;
    private LayerTargetDTO currentLayerTarget;
    private final BooleanProperty enablePaste = new SimpleBooleanProperty(false);

    public TargetConfirmController() {
        this.systemTargetService = SpringUtils.getBean(SystemTargetService.class);
        this.systemProcessService = SpringUtils.getBean(SystemProcessService.class);
        this.executor = SpringUtils.getBean(ExecutorService.class);
    }


    @Override
    public void initialize(URL location, ResourceBundle resources) {
        this.initMenuControl();
    }

    @Override
    public void initializeData(String systemId){
        this.currentSystemId = systemId;
        this.loadMenuData();
    }

    public void gotoSpecialTarget(){
        var targetView = AppStore.getEvaluationView(this.currentSystemId, SpecialTargetView.class);
        this.bodyPane.setCenter(Objects.requireNonNull(targetView).load());
        if(targetView.getController() instanceof SpecialTargetController controller){
            controller.initializeData(this.currentSystemId,this.currentLayerTarget);
        }
    }

    public void gotoStandardTarget(){
        var targetView = AppStore.getEvaluationView(this.currentSystemId, StandardTargetView.class);
        this.bodyPane.setCenter(Objects.requireNonNull(targetView).load());
        if(targetView.getController() instanceof StandardTargetController controller){
            controller.initializeData(this.currentSystemId,this.currentLayerTarget);
        }
    }
    public void refreshMenu(String layerTargetId) {
        LogUtils.info(log, "获取层面指标信息...");
        LogUtils.record(log, "请求数据，systemId：{},data:{}", this.currentSystemId, layerTargetId);
        CompletableFuture.supplyAsync(() -> systemProcessService.findTargetConfirmProcess(this.currentSystemId),this.executor)
                .thenAccept(res->Platform.runLater(()->initMenuEvalState(res)))
                .exceptionally((ex) -> {
                    log.error("获取层面指标信息出错!", ex);
                    return null;
                });
    }

    private void initMenuControl() {
        tecMenus.setCellFactory(listView -> new MenuListCell(true));
        tecMenus.getSelectionModel()
                .selectedItemProperty()
                .addListener((observable, oldValue, newValue) -> {
                    if (Objects.nonNull(newValue)) {
                        manageMenus.getSelectionModel().clearSelection();
                        this.loadPageContent(newValue);
                    }
                });

        manageMenus.setCellFactory(listView -> new MenuListCell(true));
        manageMenus.getSelectionModel()
                .selectedItemProperty()
                .addListener((observable, oldValue, newValue) -> {
                    if (Objects.nonNull(newValue)) {
                        tecMenus.getSelectionModel().clearSelection();
                        this.loadPageContent(newValue);
                    }
                });
    }

    private void loadMenuData() {
        LogUtils.info(log, "获取指标确认完成进度信息...");
        LogUtils.record(log, "请求数据:{}", this.currentSystemId);
        CompletableFuture.supplyAsync(() -> systemProcessService.findTargetConfirmProcess(this.currentSystemId), this.executor)
                .thenAccept(process -> {
                    var res = systemTargetService.findLayerTarget(this.currentSystemId);
                    Platform.runLater(() -> {
                        if (res.isSuccess()) {
                            this.initMenuData(res.getData());
                            this.initMenuEvalState(process);
                        } else {
                            MessageDialog.builder()
                                    .withContainer(this.page)
                                    .withType(MessageType.FAIL)
                                    .withMessage(res.getMsg())
                                    .build().show();
                        }
                    });
                })
                .exceptionally((ex) -> {
                    log.error("获取指标确认完成进度信息出错!", ex);
                    MessageDialog.builder()
                            .withContainer(this.page)
                            .withType(MessageType.FAIL).withMessage("加载数据表内容失败！")
                            .build().show();
                    return null;
                });
    }

    private void initMenuData(List<LayerTargetDTO> targets){
        layerTargets.clear();
        tecMenus.getItems().clear();
        manageMenus.getItems().clear();
        layerTargets.addAll(targets);
        targets.stream().filter(t -> t.getType() == TargetType.TECHNOLOGY)
                .sorted(Comparator.comparingInt(LayerTargetDTO::getSort))
                .forEach(lt -> {
                    var menuItem = new MenuVO(1,lt.getTargetId(),lt.getName(),"none-process-icon");
                    menuItem.setError(lt.getExistNotApply());
                    tecMenus.getItems().add(menuItem);
                });

        targets.stream().filter(t -> t.getType() == TargetType.MANAGEMENT)
                .sorted(Comparator.comparingInt(LayerTargetDTO::getSort))
                .forEach(lt -> {
                    var menuItem = new MenuVO(2,lt.getTargetId(),lt.getName(),"none-process-icon");
                    menuItem.setError(lt.getExistNotApply());
                    manageMenus.getItems().add(menuItem);
                });
        tecMenus.getSelectionModel().select(0);
    }

    private void initMenuEvalState(List<SystemProcessDTO> systemProcess){
        var res = systemTargetService.findLayerTarget(this.currentSystemId).getData();
        AtomicBoolean hasChange = new AtomicBoolean(false);
        tecMenus.getItems().forEach(tm->{
            var finishState = systemProcess.stream()
                    .filter(sp-> StringUtils.contains(sp.getName(),tm.getTitle()))
                    .map(SystemProcessDTO::getFinishState)
                    .findFirst().orElse(FinishState.NONE);
            tm.setIcon(ControlUtils.finishStateToIcon(finishState));
            tm.setState(finishState);
            tm.setError(hasNotApply(tm.getTitle(),res));
            hasChange.set(true);
        });
        if(hasChange.get()){
            tecMenus.refresh();
            hasChange.set(false);
        }
        manageMenus.getItems().forEach(mm->{
            var finishState = systemProcess.stream()
                    .filter(sp-> StringUtils.contains(sp.getName(),mm.getTitle()))
                    .map(SystemProcessDTO::getFinishState)
                    .findFirst().orElse(FinishState.NONE);
            mm.setIcon(ControlUtils.finishStateToIcon(finishState));
            mm.setState(finishState);
            mm.setError(hasNotApply(mm.getTitle(),res));
            hasChange.set(true);
        });
        if(hasChange.get()){
            manageMenus.refresh();
        }
    }

    private boolean hasNotApply(String name,List<LayerTargetDTO> targets){
        return targets.stream()
                .filter(t->StringUtils.equals(t.getName(),name))
                .map(LayerTargetDTO::getExistNotApply)
                .findFirst().orElse(false);
    }

    private void loadPageContent(MenuVO layerMenu){
        currentLayerTarget = this.layerTargets
                .stream()
                .filter(lt->StringUtils.equals(lt.getName(),layerMenu.getTitle()))
                .findFirst()
                .orElse(null);
        if(Objects.isNull(currentLayerTarget)){
            return;
        }
        gotoStandardTarget();
    }

}